import { Component, createContext, useContext } from "react";
import { FamilyContext, ScenarioAnalysisContext } from "./1-useState";

// 3. 父组件（类组件）：仅传递子组件，不处理 Context
export default class Parent extends Component {
  render() {
    return (
      <div
        style={{ border: "2px solid green", padding: "10px", margin: "10px" }}
      >
        <ScenarioAnalysisContext.Consumer>
          {(a) => {
            console.log(a);
            return <div> scenarionName: {a}</div>;
          }}
        </ScenarioAnalysisContext.Consumer>
        <h4>父组件（类组件）</h4>
        <p>我不处理家族数据，只传递子组件</p>
        <Grandchild /> {/* 渲染孙子组件 */}
      </div>
    );
  }
}

// 4. 孙子组件（函数组件）：消费 Context 数据
const Grandchild = () => {
  // 用 useContext 获取祖父组件提供的数据
  const scenarioAnalysisContext = useContext(ScenarioAnalysisContext);
  const { familyName, memberCount, updateCount } = useContext(FamilyContext);

  return (
    <div style={{ border: "2px solid red", padding: "10px", margin: "10px" }}>
      <h5>孙子组件（函数组件）</h5>
      <p>场景分析：{scenarioAnalysisContext}</p>
      <p>家族名称：{familyName}</p>
      <p>成员数量：{memberCount}</p>
      {/* 调用祖父组件传递的方法修改数据 */}
      <button onClick={() => updateCount(memberCount + 1)}>增加成员</button>
      <button
        onClick={() => updateCount(memberCount - 1)}
        style={{ marginLeft: "10px" }}
      >
        减少成员
      </button>
    </div>
  );
};
